import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Writer;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.Socket;


public class SocketChat {
	Queue<String> chatList = new LinkedList<String>();
	Socket socket;
	BufferedInputStream bis;
	ObjectOutputStream oos;
	Scanner scan;
	ObjectInputStream ois;
	BufferedInputStream console;
	FileWriter file;
	public SocketChat(Socket ss, FileWriter file) throws IOException{
		this.socket = ss;
		this.bis = new BufferedInputStream(ss.getInputStream());
		this.oos = new ObjectOutputStream(ss.getOutputStream());
		this.ois = new ObjectInputStream(bis);
		this.console = new BufferedInputStream(System.in);
		this.scan = new Scanner(console);
		this.file = file;
	}
	public String checkIncomingMessage() throws IOException, ClassNotFoundException{
		if (bis.available() > 0){
			Object message = ois.readObject();
			chatList.add((String) message);
			return (String) message;
		}
		return null;
	}
	public String checkOutgoingMessage() throws IOException{
		if (console.available() > 0){
			String message = scan.nextLine();
			chatList.add(message);
			return message;
		}
		return null;
	}
	public void chat() throws IOException, ClassNotFoundException{
		String s = checkIncomingMessage();
		while (s == null || s.equals("quit")){
			s = checkIncomingMessage();
			if (s != null){
				System.out.println(s);
			}
			if (s != null){
				if (s.equals("quit")){
					quit();
					System.exit(0);
				}
			}
			s = checkOutgoingMessage();
			if (s != null){
				try{
					oos.reset();
					oos.writeObject(s);
					oos.flush();
				}
				catch(java.net.SocketException e){
				}
			}
			if (s != null){
				if (s.equals("quit")){
					quit();
					System.exit(0);
				}
			}
			s = null;
		}
		System.out.println(s);
	}

	public void quit() throws IOException{
		BufferedWriter buff = new BufferedWriter(file);
		while (!chatList.isEmpty()){
			buff.write(chatList.remove());
		}
		socket.close();
		buff.close();
		file.close();
	}
}